﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Xml;
using System.Configuration;
using System.Timers;
using System.Data;
using System.Xml.Serialization;
using System.IO;
using CommonLibrary.XML;
using log4net;

namespace Translate
{
    public class YouDaoTranslate
    {
        private static ILog _log = LogManager.GetLogger(typeof(YouDaoTranslate));
        string keyfrom = "";
        string key = "";
        //string keyfrom = ConfigurationManager.AppSettings["keyfrom"];
        //string key = ConfigurationManager.AppSettings["key"];
        string ProxyUser = ConfigurationManager.AppSettings["ProxyUser"];
        string ProxyPassWord = ConfigurationManager.AppSettings["ProxyPassWord"];
        int cCount = 0;
        Timer timer = new Timer(5000);
        DataSet ds = new DataSet();
        public YouDaoTranslate()
        {
            ds.ReadXml("Keylist.xml");
            timer.Enabled = true;
            timer.Elapsed += new ElapsedEventHandler(timerElapsed);
        }
        void timerElapsed(object sender, ElapsedEventArgs e)
        {
            cCount = 0;
            ds.WriteXml("Keylist.xml", XmlWriteMode.WriteSchema);
        }
        int ckIndex = 0;
        private void GetAPIKey(out string key, out string keyfrom)
        {
            key = "";
            keyfrom = "";
            if (ds != null && ds.Tables.Count > 0)
            {
                int transCount = 0;
                DateTime oclock = new DateTime();
                int keycount = ds.Tables[0].Rows.Count;
                if (keycount == ckIndex) ckIndex = 0;
                while (keycount > ckIndex)
                {
                    DataRow dr = ds.Tables[0].Rows[ckIndex];
                    ckIndex++;
                    transCount = int.Parse(dr["TransCount"].ToString());
                    oclock = DateTime.Parse(dr["OClock"].ToString());
                    if (DateTime.Now < oclock.AddHours(1) && transCount > 950)
                    {
                    }
                    else
                    {
                        key = dr["APIkey"].ToString();
                        keyfrom = dr["keyfrom"].ToString();
                        if (DateTime.Now > oclock.AddHours(1))
                        {
                            dr["OClock"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                            dr["TransCount"] = "1";
                        }
                        else
                        {
                            dr["TransCount"] = (transCount + 1).ToString();
                        }
                        break;
                    }
                }
            }
            cCount++;
        }
        public string YDTranslate(string sstr)
        {
            GetAPIKey(out   key, out   keyfrom);
            if (cCount == 20)
            {
                timerElapsed(null, null);
            }
            else if (key == "")
            {
                throw new Exception("超过每小时1000次翻译限制!");
            }
            if (string.IsNullOrEmpty(sstr.Trim())) return "";
            int i = 0;
            string res = "";
            int addcount = 180;
            while (i < sstr.Length)
            {
                int trueindex = 0;
                string sunstr = "";
                if (i + 180 < sstr.Length)
                {
                    sunstr = sstr.Substring(i, addcount);
                    trueindex = sunstr.LastIndexOf(' ');
                    if (trueindex == 0) trueindex = addcount;
                    sunstr = sstr.Substring(i, trueindex);
                }
                else
                {
                    sunstr = sstr.Substring(i, sstr.Length - i);
                }
                if (trueindex == 0) trueindex = addcount;
                res += Translate(sunstr);
                cCount++;
                i += trueindex;
            }
            return res;
        }
        /// <summary>
        /// 英汉词典
        /// 调用有道翻译接口
        /// 需连接上互联网
        /// </summary>
        /// <param name="from">待翻译字符传UTF-8编码，长度小于200</param>
        /// <returns></returns>
        public string Dictionary(string from)
        {
            GetAPIKey(out   key, out   keyfrom);
            string fd = "";
            try
            {
                if (from.Length >= 200 || from.Trim() == "") return "";
                string strUrl = @"http://fanyi.youdao.com/openapi.do?keyfrom=" + keyfrom + "&key=" + key + "&type=data&doctype=xml&version=1.1&q="; //获得IP的网址了      
                strUrl += from;
                Uri uri = new Uri(strUrl);
                WebRequest wr = WebRequest.Create(uri);
                wr.Proxy = WebRequest.GetSystemWebProxy();
                wr.Proxy.Credentials = new NetworkCredential(ProxyUser, ProxyPassWord);
                System.IO.Stream s = wr.GetResponse().GetResponseStream();
                System.IO.StreamReader sr = new System.IO.StreamReader(s, Encoding.UTF8);
                string all = sr.ReadToEnd(); //读取网站的数据                 
                youdaofanyi obj = (youdaofanyi)XMLEncodeHelper.Deserialize(all, typeof(youdaofanyi));
                if (obj.errorCode == 0)
                {
                    fd += "<!-- 翻译 -->\r\n";
                   
                    fd += obj.translation.paragraph;
                   
                    if (obj.basic != null)
                    {
                        fd += "\r\n<!-- 基本释义 -->\r\n";
                        foreach (string str in obj.basic.explains)
                        {
                            fd += str + "\r\n";
                        }
                    }
                    if (obj.web != null)
                    {
                        fd += "\r\n<!-- 网络释义 -->\r\n";
                        foreach (youdaofanyiExplain yfe in obj.web)
                        {
                            fd += yfe.key + "\r\n";
                            foreach (string strv in yfe.value)
                            {
                                fd += strv + "\r\n";
                            }
                        }
                    }
                }
                else
                {
                    fd = "<" + from + ">" + "<翻译失败！错误码：>" + obj.errorCode;
                }
            }
            catch (Exception ex)
            {
                _log.Error(ex.ToString());
                fd = "<" + from + ">" + "<翻译失败！>";
            }
            return fd;       
        }     
        /// <summary>
        /// 调用有道翻译接口
        /// 需连接上互联网
        /// </summary>
        /// <param name="from">待翻译字符传UTF-8编码，长度小于200</param>
        /// <returns></returns>
        private string Translate(string from)
        {
            string fd = "";
            try
            {
                if (from.Length >= 200 || from.Trim() == "") return "";

                string strUrl = @"http://fanyi.youdao.com/openapi.do?keyfrom=" + keyfrom + "&key=" + key + "&type=data&doctype=xml&version=1.1&q="; //获得IP的网址了      
                strUrl += from;
                Uri uri = new Uri(strUrl);
                WebRequest wr = WebRequest.Create(uri);
                wr.Proxy = WebRequest.GetSystemWebProxy();
                wr.Proxy.Credentials = new NetworkCredential(ProxyUser, ProxyPassWord);
                System.IO.Stream s = wr.GetResponse().GetResponseStream();
                System.IO.StreamReader sr = new System.IO.StreamReader(s, Encoding.UTF8);
                string all = sr.ReadToEnd(); //读取网站的数据    
                youdaofanyi obj = (youdaofanyi)XMLEncodeHelper.Deserialize(all, typeof(youdaofanyi));
                if (obj.errorCode == 0)
                    fd = obj.translation.paragraph;
                else
                {
                    fd = "<" + from + ">" + "<翻译失败！错误码：>" + obj.errorCode;
                }
            }
            catch (Exception ex)
            {
                _log.Error(ex.ToString());
                fd = "<" + from + ">" + "<翻译失败！>";
            }
            return fd;
        }
        public ElapsedEventHandler timer_Elapsed
        {
            get;
            set;
        }
    }
}
